<!-- 
	动态组件：商品分类
	props: 
		data: 组件数据
		
	action:
		
 -->
<template>
    <view class="dynamic-category">
        <view class="main-dom product-main">
            <scroll-view class="product-main-nav" scroll-y="true" :style="{ height: listHeight }">
                <nav-tree :tree-data="classifyList" :active-id="activeId" @treeClickEvent="treeClickEvent"> </nav-tree>
            </scroll-view>
            <swiper
                class="swiper product-main-list"
                :class="tempType == 1 ? 'p-b-120' : ''"
                :style="{ height: listHeight }"
                :current="tabIndex"
                @change="swiperChange">
                <swiper-item v-for="(swiperItem, swiperIndex) in tabs" :key="swiperIndex">
                    <product-list
                        :ref="'productList_' + swiperIndex"
                        :requestData="requestData"
                        :height="listHeight"
                        :isHideProImg="isHideProImg"
                        @sku="sku"
                        @amountProp="amountProp"
                        :infoType="swiperIndex"
                        :displayData="displayData"
                        :tempType="tempType"
                        :isOnShow="isOnShow"
                        @upFavorite="upFavorite"
                        @isUpNum="isUpNum"
                        :isClass="isClass"
                        @loadNoMoreBack="loadNoMoreBack">
                    </product-list>
                </swiper-item>
            </swiper>
        </view>
    </view>
</template>

<script>
import { mapGetters } from "vuex"
import searchBar from "@/components/common/search-bar.vue"
import tabBar from "@/components/common/tab-bar.vue"
import productListFilter from "@/components/product/product-list-filter.vue"
import productList from "@/components/product/product-list.vue"
import navTree from "@/components/product/nav-tree.vue"
import productSpec from "@/components/product/product-spec.vue"
import navTreeX from "@/components/product/nav-tree-x.vue"
import navFirst from "@/components/product/nav-first.vue"
import { getElementHeight, getElementTop } from "@/uni-sub-base/utils/elementUtil.js"
import { getProductDisplay } from "@/utils/appInit.js"

import { getProductTypeTree, productBrandList, getTagList } from "@/service/api/product.js"
import config from "@/config/config.js"
import numPopup from "@/components/order/num-popup.vue"
import utilsOld from "@/utils/utilsOld.js"
import { updateCart } from "@/utils/cartUtil.js"
export default {
    components: {
        productList,
        navTree,
        productSpec,
    },
    props: {
        data: {
            type: Object,
            default: () => {},
        },
        //列表位置 0商品 1无单退货
        tempType: {
            type: Number,
            default: 0,
        },
        isOnShow: {
            type: Boolean,
            default: true,
        },
        isClass: {
            type: Boolean,
            default: false,
        },
        isLimit: {
            type: Boolean,
            default: false,
        },
        currentClass: {
            type: String,
            default: "0",
        },
        productTagId: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            popinputAmount: "",
            inputAmount: "",
            numPopShow: false,
            initClassify: false,
            activeId: -1,
            classifyList: [],
            secondClassifyList: [],
            isFold: true,
            skuModel: false,
            isHideProImg: false,
            actions: [],
            placeholderText: "请输入商品名称",
            searchValue: "",
            tabIndex: 0,
            tabs: [
                {
                    title: "综合",
                },
            ],
            navHeight: 0, //nav所需高度
            listHeight: "100vh", //list所需高度
            listHeight1: 0, //list所需高度
            listHeightNoneSub: 0, //list所需高度
            initHeight: 0,
            productDatas: [],
            navItems: [],
            currentNav: 0,
            isloadding: false,
            loadOk: false,
            // sku 商品规格弹窗
            optPopup: {
                data: {},
                type: "",
                change: false,
                show: true,
            },
            isClosePop: false,
            treeOk: false,
            tags: [],
            brands: [],
            // 请求参数
            requestData: {
                ProductType: 1,
                OrderBy: "display_sequence",
                Sort: "desc",
            },
            displayData: {},
            showPopSku: true,
            timer: null,
            isUp: true,
            isShowFilter: false,
            popTop: "",
            popite: {},
            popitem: {},
            poptype: null,
            popdisplayData: {},
            poprefresh: false,
            isShowFilter: false,
            popTop: "",
            tagId: "",
            totalClassify: {},
            isFocus: false,
            selectionStart: -1,
            selectionEnd: 0,
        }
    },
    watch: {
        //监听购物车数据
        getUpView(e) {
            //获取总数
            this.refresh()
        },
        productTagId(e) {
            //获取总数
            if (e) {
                this.tagId = e
                this.checkIsFrom(e)
            }
        },
    },
    computed: {
        ...mapGetters(["getUpView"]),
    },
    onShow() {
        //多选规格批量操作回来返回UI处理
        //#ifdef MP
        let pages = getCurrentPages()
        let currPage = pages[pages.length - 1] //当前页
        // 直接用this.currPage.data去取B页面传递过来的数据
        this.isClosePop = currPage.data.isClosePop
        //#endif

        if (this.isClosePop) {
            this.$refs.popSku.close()
            this.isClosePop = false
        }
    },
    mounted() {
        this.getProductTypeTree()
        this.productBrandList()
        this.getTagList()
        this.GetProductDisplay()
        if (this.getMenuStyle() == 1) {
            this.actions = [
                {
                    type: "cart",
                    id: 2,
                    iconType: 1,
                },
            ]
            this.getTop()
        }
        this.tagId = this.productTagId
    },
    methods: {
        popAmountClose() {
            this.$refs.popAmountTip.close()
            this.blurFn()
        },
        popAmountConfirm() {
            this.inputAmount = this.popinputAmount
            this.popite.Amount = this.popinputAmount
            this.changeAmountFn(this.popite, this.popitem, this.poptype, this.popdisplayData)
        },
        changeAmountFn(item, ite, type, popdisplayData) {
            var that = this
            let num = Number(item.Amount)
            let stock = item.Stock
            let minNum = ite.MinNum
            let UnitRatio = item.Ratio
            let LimitBuy = ite.LimitBuy
            let addNum = ite.AddNum
            const _oldAmount = item.Amount

            if (popdisplayData.NoCheckStock) {
                if (type != 0) {
                    item.Amount = num + Number(type)
                } else {
                    item.Amount = num
                }
                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            this.poprefresh = true
            this.$nextTick(() => {
                this.poprefresh = false
            })
            this.$forceUpdate()
            this.isUpNum(false)
            //商品
            if (_oldAmount !== item.Amount || type === 0) {
                const _obj = {}
                _obj.ProductId = item.ProductId
                _obj.Amount = item.Amount
                _obj.SkuId = item.SkuId
                _obj.UnitId = item.UnitId
                _obj.UnitName = item.UnitName
                _obj.Ratio = item.Ratio
                let param = []
                param.push(_obj)
                updateCart(param, false, true).then((res) => {})
            }
            setTimeout((e) => {
                that.$refs.popAmountTip.close()
                this.blurFn()
            }, 500)
        },
        blurFn() {
            this.$nextTick(() => {
                this.isFocus = false
                this.selectionStart = -1
                this.selectionEnd = -1
            })
        },
        foldToggle() {
            const that = this
            that.isFold = !this.isFold
            that.$nextTick(function () {
                that.getClassifyHeight()
            })
        },
        choseClassify(item) {
            if (this.activeId !== item.id) {
                this.resetClass(item, false)
            }
        },
        getTop() {
            getElementTop(this, ".pop", (e) => {
                this.popTop = e
            })
        },
        // 获取整体显示设置
        GetProductDisplay() {
            getProductDisplay().then((res) => {
                if (res) {
                    this.displayData = res.Data
                }
            })
        },
        //标签
        getTagList() {
            let param = {}
            getTagList(param).then((res) => {
                this.tags = res.Data
                this.checkIsFrom()
                this.$forceUpdate()
            })
        },
        //品牌
        productBrandList() {
            let param = {}
            productBrandList(param).then((res) => {
                this.brands = res.Data
                this.$forceUpdate()
            })
        },
        //商品分类树列表
        getProductTypeTree() {
            let param = {
                InfoType: 1,
                parent_path: "_0_2_",
            }
            getProductTypeTree(param).then((res) => {
                this.getNavData(res)
            })
        },
        getNavData(res) {
            if (res) {
                this.initClassify = false
                this.classifyList = []

                if (this.isClass) {
                    let classId = Number(this.currentClass)
                    let classPath = ""
                    if (res.Data.children && res.Data.children.length > 0) {
                        res.Data.children.forEach((item) => {
                            if (item.id == classId) {
                                classPath = item.parent_path
                            }
                            this.classifyList.push(item)
                        })
                    }
                    this.activeId = classId
                    this.requestData.typePath = classPath
                } else {
                    this.totalClassify = {
                        OrderBy: res.Data.OrderBy,
                        id: res.Data.id,
                        name: res.Data.name,
                        parent_id: res.Data.parent_id,
                        parent_path: res.Data.parent_path,
                        type_id: res.Data.type_id,
                    }
                    this.classifyList.push(this.totalClassify)
                    if (res.Data.children && res.Data.children.length > 0) {
                        res.Data.children.forEach((item) => {
                            this.classifyList.push(item)
                        })
                    }
                    this.activeId = res.Data.id
                    this.requestData.typePath = res.Data.parent_path
                }
                //#ifndef MP
                setTimeout(() => {
                    this.refresh()
                }, 300)
                //#endif
                this.checkIsFrom()
            }
        },
        checkIsFrom(tagId) {
            if (this.tagId) {
                let ids = []
                this.tags.forEach((e) => {
                    if (e.Id == this.tagId) {
                        e.checked = true
                        ids.push(this.tagId)
                    } else {
                        e.checked = false
                    }
                })
                this.requestData.TagIds = ids.join(",")
                this.refresh()
                this.$nextTick(() => {
                    this.$emit("productTagId", "")
                })
            }
        },
        //刷新列表
        refresh() {
            if (this.getMenuStyle() == 0 || this.getMenuStyle() == 2) {
                if (this.$refs.productList_0 && this.$refs.productList_0[0]) {
                    this.$refs.productList_0[0].refresh(this.requestData)
                }
                if (this.$refs.productList_1 && this.$refs.productList_1[0]) {
                    this.$refs.productList_1[0].refresh(this.requestData)
                }
                if (this.$refs.productList_2 && this.$refs.productList_2[0]) {
                    this.$refs.productList_2[0].refresh(this.requestData)
                }
                if (this.$refs.productList_3 && this.$refs.productList_3[0]) {
                    this.$refs.productList_3[0].refresh(this.requestData)
                }
            } else if (this.getMenuStyle() == 1) {
                this.$refs.swiperIndex.refresh(this.requestData)
            }
        },
        //收藏触发更新
        upFavorite(infoType) {
            if (infoType == 2) {
                if (this.$refs.productList_0 && this.$refs.productList_0[0]) {
                    this.$refs.productList_0[0].refresh(this.requestData)
                }
            } else if (infoType == 0) {
                if (this.$refs.productList_2 && this.$refs.productList_2[0]) {
                    this.$refs.productList_2[0].refresh(this.requestData)
                }
            }
        },
        getClassifyHeight() {
            if (this.secondClassifyList && this.secondClassifyList.length > 0) {
                const query = uni.createSelectorQuery().in(this)
                query
                    .select(".secondClassify")
                    .boundingClientRect((data) => {
                        let dataHeight = 0
                        if (data) {
                            dataHeight = Number(data.height)
                        }
                        this.listHeight1 = Number(this.initHeight) - dataHeight + "px"
                    })
                    .exec()
            } else {
                this.listHeight1 = this.listHeightNoneSub
            }
        },

        searchFn(searchText) {
            //搜索
            this.requestData.search = searchText

            if (this.isClass) {
                this.requestData.BrandIds = ""
                this.cancelFilterBrands()
                this.resetClass(this.classifyList[0])
            } else {
                this.$refs.productFilter.reSet()
                this.requestData.BrandIds = ""
                this.requestData.TagIds = ""
                this.resetClass(this.classifyList[0])
            }

            if (this.getMenuStyle() == 0 || this.getMenuStyle() == 2) {
                this.$refs.productFilter.hideAllPop()
            }
        },
        resetClass(item, bool = true) {
            const that = this
            if (bool) {
                that.secondClassifyList = item.children || []
                that.isFold = true
            } else {
                if (item.children && item.children.length > 0) {
                    that.secondClassifyList = item.children
                    that.isFold = true
                }
            }
            that.activeId = item.id
            that.typePath = item.parent_path
            that.requestData.typePath = item.parent_path

            if (!that.isUp) {
                that.$emit("upCart", true)
                that.isUp = true
            }
            that.$nextTick(function () {
                that.getClassifyHeight()
            })
            that.refresh()
        },
        goCart() {
            uni.navigateTo({
                url: "/pages/cart/cartTemp",
            })
        },
        actionFn(actionItem) {
            //功能点击
            if (actionItem.id == 1) {
                //扫一扫
                this.scan()
            } else if (actionItem.id == 2) {
                //进入购物车
                this.goCart()
            }
            if (this.getMenuStyle() == 0 || this.getMenuStyle() == 2) {
                this.$refs.productFilter.hideAllPop()
            } else if (this.getMenuStyle() == 1) {
                this.isShowFilter = false
            }
        },
        scan() {
            //扫一扫
            //#ifdef MP||APP-PLUS
            // 允许从相机和相册扫码
            uni.scanCode({
                success: function (res) {
                    uni.showToast({
                        title: "扫码结果:" + res.result,
                        icon: "none",
                        duration: 2000,
                    })
                },
            })
            //#endif
        },
        changeListTheme(isShow) {
            //切换商品列表无图显示
            this.displayData.IsShowImg = isShow
            this.$forceUpdate()
        },
        sku(item) {
            this.showPopSku = true
            this.optPopup.type = "attr"
            this.optPopup.data = item
            this.$refs.popSku.open()
        },
        amountProp(ite, item, type, displayData) {
            this.popite = ite
            this.popitem = item
            this.poptype = type
            this.popdisplayData = displayData
            if (ite.Amount == 0) {
                this.popinputAmount = 0
            } else {
                this.popinputAmount = ite.Amount
            }
            this.$refs.popAmountTip.open()
            setTimeout((e) => {
                this.isFocus = true
                this.selectionStart = 0
                this.selectionEnd = this.popinputAmount.toString().length
            }, 100)
        },
        addCart(e) {
            this.$refs.popSku.close()
        },
        addCartBatch(e) {},
        addBatch(e) {
            this.$refs.popSku.close()
            this.$refs.popBatch.open()
        },
        buyNow() {},
        swiperChange(e) {
            let tabIndex = e.detail.current
            this.clickTab(tabIndex)
        },
        //tab切换
        clickTab(index) {
            if (this.tabIndex != index) {
                clearTimeout(this.timer)
                this.timer = setTimeout((time) => {
                    this.tabIndex = index
                    this.requestData.infoType = index
                }, 20)
                if (!this.isUp) {
                    this.$emit("upCart", true)
                    this.isUp = true
                }
            }
            this.$refs.productFilter.hideAllPop()
        },
        // 点击分类事件
        treeClickEvent(item) {
            if (this.activeId !== item.id) {
                this.resetClass(item)
            }
        },
        closePopup() {
            this.$refs.popSku.close()
        },
        setCarListFunc() {
            this.$forceUpdate()
        },
        closePopupBatch() {
            this.$refs.popBatch.close()
        },
        setCarListFuncBatch() {
            this.$forceUpdate()
        },
        filterFn(data) {
            this.requestData.OrderBy = data.OrderBy
            this.requestData.Sort = data.Sort
            this.refresh()
        },
        filterBrandFn(data) {
            let ids = []
            data.forEach((e) => {
                if (e.checked) {
                    ids.push(e.Id)
                }
            })
            this.requestData.BrandIds = ids.join(",")
            this.refresh()
        },
        filterTagFn(data) {
            let ids = []
            data.forEach((e) => {
                if (e.checked) {
                    ids.push(e.Id)
                }
            })
            this.requestData.TagIds = ids.join(",")
            this.refresh()
        },
        skuChange(e) {
            if (!e.show) {
                this.showPopSku = false
                // this.$nextTick(e=>{
                // 	this.showPopSku = true
                // })
            }
        },
        isUpNum(e) {
            this.isUp = e
        },
        getMenuStyle() {
            if (this.isClass) {
                return 1
            }
            if (this.displayData && typeof this.displayData.CategoryStyle == "number") {
                return this.displayData.CategoryStyle
            }
            return config.appSet.proMenuStyle
        },
        getIsFilter() {
            let isFilter =
                (this.requestData.BrandIds && this.requestData.BrandIds != "") ||
                (this.requestData.minPrice && this.requestData.minPrice != 0) ||
                (this.requestData.maxPrice && this.requestData.maxPrice != 0)
            return isFilter
        },
        // 修改品牌筛选
        changeBrand(item, index) {
            this.brands[index].checked = !this.brands[index].checked
            this.$forceUpdate()
        },
        filterBrandFn1() {
            this.hideBrandPop()
            let ids = []
            this.brands.forEach((e) => {
                if (e.checked) {
                    ids.push(e.Id)
                }
            })
            this.requestData.BrandIds = ids.join(",")
            this.refresh()
        },
        hideBrandPop() {
            this.isShowFilter = false
        },
        cancelFilterBrands() {
            this.brands.forEach((e) => {
                e.checked = false
            })
            this.requestData.minPrice = 0
            this.requestData.maxPrice = 0
            this.$forceUpdate()
        },
        loadNoMoreBack(e) {
            if (e) {
                let objItem = {}
                let hasIn = false
                if (!this.classifyList || this.classifyList.length < 1) {
                    return
                }
                if (this.activeId == this.classifyList[0].id) {
                    //当前是全部分类
                    this.treeClickEvent(this.classifyList[1])
                } else {
                    for (var i = 0; i < this.classifyList.length; i++) {
                        let item = this.classifyList[i]
                        if (item.id == this.activeId) {
                            //判断当前是否是大类
                            this.hasIn = true
                            if (i != this.classifyList.length - 1) {
                                objItem = this.classifyList[i + 1]
                            } else {
                                objItem = this.classifyList[0]
                            }
                            this.treeClickEvent(objItem)
                            return
                        }
                    }
                    if (!hasIn) {
                        for (var i = 1; i < this.classifyList.length; i++) {
                            let item = this.classifyList[i]
                            let path = item.parent_path
                            if (this.typePath.includes(path)) {
                                let item = this.classifyList[i]
                                if (i != this.classifyList.length - 1) {
                                    objItem = this.classifyList[i + 1]
                                } else {
                                    objItem = this.classifyList[0]
                                }
                                this.treeClickEvent(objItem)
                                return
                            }
                        }
                    }
                }
            }
        },
    },
}
</script>

<style lang="scss" scope>
@import "@/uni-sub-base/components/dynamic/style/dynamic.scss";
.product-main {
    display: flex;
    flex-direction: row;
    position: sticky;
    top: 0;
    .product-main-nav {
        display: flex;
        flex: 1.1;
        flex-direction: column;
        background: $uni-bg-color-grey;
    }

    .product-main-list {
        // display: flex;
        flex: 3.5;
        // justify-content: center;
        background: $uni-bg-color-grey;
    }

    .p-b-120 {
        padding-bottom: 120rpx;
    }
}
</style>
